import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators
} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import {AccountService} from '../../account/account.service';
import {ActivatedRoute, Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {StoreProductService} from '../store-product.service';

@Component({
  selector: 'app-modify',
  templateUrl: './modify.component.html',
  styleUrls: ['./modify.component.scss'],
  providers: [StoreProductService, AccountService]
})
export class ModifyComponent implements OnInit {

  order_no;
  expressInfo;
  validateForm: FormGroup;
  _isSpinning = true;
  hadGeCityList;
  hadGetRegionList;
  provinceOptions;
  cityOptions;
  regionOptions;

  constructor(private orderService: StoreProductService,
              private _message: NzMessageService,
              private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private accountService: AccountService) {
    this.validateForm = this.fb.group({
      order_no: [ null, [ Validators.required ] ],
      name: [ '', [ Validators.required ] ],
      mobile:      [ '', [ Validators.required ], [this.mobileValidator] ],
      Province: [ null, [ Validators.required ] ],
      City: [ null, [ Validators.required ] ],
      district: [ null, [ Validators.required ] ],
      detail: [ null, [ Validators.required ] ],
    });

    this.validateForm.controls.Province.valueChanges
      .subscribe(res2 => {
        if (!res2) {
          // return;
        } else {
          this.getCityList();
        }
      });

    this.validateForm.controls.City.valueChanges
      .subscribe(res2 => {
        if (!res2) {
          // return;
        } else {
          this.getRegionList();
        }
      });
  }

  ngOnInit() {
    this.order_no = this.route.snapshot.params['id'];
    this.validateForm.controls['order_no'].setValue(this.order_no);

    this.getProvinceList();
    this.getExpressInfo();
  }

  mobileValidator = (control: FormControl): any => {
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (!(/(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/).test(control.value)) {
          observer.next({error: true, mobile: true});
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 500);
    });
  }

  // 获取发货信息
  getExpressInfo() {
    this.orderService.getExpressInfo(this.order_no).subscribe(res => {
      if (res.code === 2000) {
        this.expressInfo = res.data;
        res.data.applet_member_address = JSON.parse(res.data.applet_member_address );
        this._isSpinning = false;
        this.validateForm.controls['name'].setValue(res.data.name);
        this.validateForm.controls['mobile'].setValue(res.data.mobile);
        this.validateForm.controls['Province'].setValue(res.data.applet_member_address.province);
        this.validateForm.controls['City'].setValue(res.data.applet_member_address.city);
        this.validateForm.controls['district'].setValue(res.data.applet_member_address.district);
        this.validateForm.controls['detail'].setValue(res.data.applet_member_address.detail);
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  getProvinceList() {
    this.accountService.getProvinceList().subscribe(res => {
      this.provinceOptions = res.data;
    });
  }

  getCityList() {
    if (this.provinceOptions) {
      let code;
      this.provinceOptions.forEach(val => {
        if (val.name === this.validateForm.controls['Province'].value) {
          code = val.code;
        }
      });
      this.accountService.getCityList(code).subscribe(res => {
        this.cityOptions = res.data;
        if (!this.hadGeCityList) {
          this.hadGeCityList = true;
        } else {
          this.validateForm.controls.City.reset();
        }
      });
    } else {
      setTimeout(() => {
        this.getCityList();
      }, 500);
    }

  }

  getRegionList() {
    if (this.cityOptions) {
      let code;
      this.cityOptions.forEach(val => {
        if (val.name === this.validateForm.controls['City'].value) {
          code = val.code;
        }
      });
      this.accountService.getRegionList(code).subscribe(res => {
        this.regionOptions = res.data;
        if (!this.hadGetRegionList) {
          this.hadGetRegionList = true;
        } else {
          this.validateForm.controls.district.reset();
        }
      });
    } else {
      setTimeout(() => {
        this.getRegionList();
      }, 500);
    }
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    console.log(this.validateForm);
    if (this.validateForm.valid) {
      this.orderService.editExpressAddress(this.validateForm.value).subscribe(res => {
        if (res.code === 2000) {
          this._message.create('success', '修改成功');
          setTimeout(() => {
            this.router.navigate(['/member/order/list']);
          }, 1000);
        } else {
          this._message.create('error', res.message);
        }
      });
    }
  }
}
